import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/user_model.dart';
import '../../core/models/travel_log_model.dart';
import '../../core/models/topic_model.dart';
import '../../core/providers/user_provider.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/topic_provider.dart';

class PersonalProfileScreen extends ConsumerStatefulWidget {
  const PersonalProfileScreen({super.key});

  @override
  ConsumerState<PersonalProfileScreen> createState() =>
      _PersonalProfileScreenState();
}

class _PersonalProfileScreenState extends ConsumerState<PersonalProfileScreen>
    with SingleTickerProviderStateMixin {
  int _selectedTabIndex = 0;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _selectedTabIndex = _tabController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child:
              currentUser == null
                  ? _buildLoginPrompt()
                  : _buildMainContent(currentUser),
        ),
      ),
    );
  }

  Widget _buildLoginPrompt() {
    return [
      Spacer(),
      Container(
        width: 120.w,
        height: 120.w,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/logo.png'),
            fit: BoxFit.contain,
          ),
        ),
      ).center(),
      SizedBox(height: 24.h),
      Text(
        'Please login to view profile',
        style: TextStyle(
          fontSize: 18.sp,
          color: Colors.white,
          fontWeight: FontWeight.w600,
          fontFamily: 'PoetsenOne',
        ),
      ).center(),
      SizedBox(height: 32.h),
      Container(
        width: 200.w,
        height: 48.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24.r),
        ),
        child:
            Text(
              'Login',
              style: TextStyle(
                fontSize: 16.sp,
                color: Color(0xFF1A1A1A),
                fontWeight: FontWeight.w600,
                fontFamily: 'PoetsenOne',
              ),
            ).center(),
      ).inkWell(onTap: () => GoRouter.of(context).push('/login')).center(),
      Spacer(),
    ].toColumn();
  }

  Widget _buildMainContent(UserDataEntity currentUser) {
    return [
      _buildHeaderSection(),

      Expanded(
        child: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child:
                    [
                      SizedBox(height: 20.h),
                      _buildUserInfoContainer(currentUser),
                      SizedBox(height: 24.h),
                      _buildTabSection(),
                      SizedBox(height: 16.h),
                    ].toColumn(),
              ),
            ];
          },
          body: _buildTabContent(currentUser),
        ),
      ),
    ].toColumn();
  }

  Widget _buildHeaderSection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child:
          [
            Text(
              'Personal',
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontFamily: 'PoetsenOne',
              ),
            ),
            Spacer(),
            Container(
              width: 30.w,
              height: 30.h,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    AliIcons.iconSetting,
                    color: Color(0xFFFDF5E1),
                    size: 20.sp,
                  ).center(),
            ).inkWell(
              onTap: () {
                GoRouter.of(context).push('/settings');
              },
            ),
          ].toRow(),
    );
  }

  Widget _buildUserInfoContainer(UserDataEntity currentUser) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFFDDB31),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: [
        _buildUserInfoRow(currentUser),
        SizedBox(height: 16.h),

        Text(
          'Having Seen The Flowers And Scenery Today, I Hope You Will Also Have The Same Sunshine.',
          style: TextStyle(fontSize: 14.sp, color: Colors.black87, height: 1.4),
        ),
        SizedBox(height: 16.h),

        _buildVisitorContainer(),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildUserInfoRow(UserDataEntity currentUser) {
    return [
      Container(
        width: 81.w,
        height: 81.h,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.black, width: 2.w),
          image: DecorationImage(
            image: AssetImage(
              currentUser.avatar.isNotEmpty
                  ? currentUser.avatar
                  : 'assets/resources/default_avatar.png',
            ),
            fit: BoxFit.cover,
          ),
        ),
      ),
      SizedBox(width: 16.w),

      Expanded(
        child: [
          Text(
            currentUser.username.isNotEmpty
                ? currentUser.username
                : 'Rose Wade',
            style: TextStyle(
              fontSize: 18.sp,
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 4.h),
          Text(
            'Last Login: August 8, 2025',
            style: TextStyle(fontSize: 12.sp, color: Colors.black54),
          ),
        ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
      ),

      Container(
        width: 32.w,
        height: 32.h,
        decoration: BoxDecoration(color: Colors.black, shape: BoxShape.circle),
        child:
            Icon(AliIcons.iconEdit, color: Colors.white, size: 18.sp).center(),
      ).inkWell(
        onTap: () {
          GoRouter.of(context).push('/edit-profile');
        },
      ),
    ].toRow();
  }

  Widget _buildVisitorContainer() {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    final visitors = allUsers.take(5).toList();

    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
      ),
      padding: EdgeInsets.only(bottom: 2.w, right: 2.w),
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(width: 1.w, color: Colors.black),
        ),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            [
              SizedBox(
                width: 150.w,
                height: 42.h,
                child: Stack(
                  children: [
                    for (int i = 0; i < visitors.length; i++)
                      Positioned(
                        left: (i * 25).toDouble().w,
                        child: _buildVisitorAvatar(visitors[i].avatar),
                      ),
                  ],
                ),
              ),
              SizedBox(width: 6.w),

              Text(
                'Visited home page',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.black87,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ].toRow(),

            Positioned(
              top: 6.h,
              right: -16.w,
              child: Image.asset(
                'assets/resources/eyes.png',
                width: 40.w,
                height: 33.h,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVisitorAvatar(String imagePath) {
    return Container(
      width: 42.w,
      height: 42.h,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.black, width: 1.w),
        image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.cover),
      ),
    );
  }

  Widget _buildTabSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: [
        _buildTabItem(0, 'assets/resources/home_topic.png'),
        _buildTabItem(1, 'assets/resources/home_share.png'),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceAround),
    );
  }

  Widget _buildTabItem(int index, String imagePath) {
    final isSelected = _selectedTabIndex == index;

    return [
      Image.asset(
        imagePath,
        width: 60.w,
        height: 30.h,
        color: isSelected ? null : Colors.white.withValues(alpha: 0.6),
        colorBlendMode: isSelected ? null : BlendMode.modulate,
      ),
      if (isSelected) ...[
        SizedBox(height: 8.h),
        Image.asset(
          'assets/resources/home_select.png',
          width: 40.w,
          height: 8.h,
        ),
      ],
    ].toColumn().inkWell(
      onTap: () {
        _tabController.animateTo(index);
      },
    );
  }

  Widget _buildTabContent(UserDataEntity currentUser) {
    return TabBarView(
      controller: _tabController,
      children: [
        _buildTopicContent(currentUser),
        _buildShareContent(currentUser),
      ],
    );
  }

  Widget _buildTopicContent(UserDataEntity currentUser) {
    final topics = ref.watch(outingTopicProvider);
    final userTopics =
        topics.where((topic) => topic.userId == currentUser.id).toList();

    if (userTopics.isEmpty) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child:
            Image.asset(
              'assets/resources/no.png',
              width: 176.w,
              height: 176.w,
            ).center(),
      );
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: userTopics.length,
        itemBuilder: (context, index) {
          final topic = userTopics[index];
          return _buildTopicItem(topic, index);
        },
      ),
    );
  }

  Widget _buildTopicItem(OutingTopicEntity topic, int index) {
    final isOdd = (index + 1) % 2 == 1;
    final backgroundImage =
        isOdd
            ? 'assets/resources/topic_card_bg_1.png'
            : 'assets/resources/topic_card_bg_2.png';

    return Container(
      height: 94.h,
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(backgroundImage),
          fit: BoxFit.fill,
        ),
      ),
      child: [
        Container(
          width: 54.w,
          height: 54.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Color(0xFF2AB061),
          ),
          child:
              Image.asset(
                'assets/resources/topic_icon.png',
                width: 28.w,
                height: 28.w,
              ).center(),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: [
            Text(
              topic.description,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.black,
                height: 1.3,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ).center(),
          ].toColumn(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
          ),
        ),
      ].toRow(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
      ),
    ).inkWell(
      onTap: () {
        GoRouter.of(context).push('/topic-detail/${topic.topicId}');
      },
    );
  }

  Widget _buildTravelLogCard(TravelLogEntity travelLog) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final currentUser = ref.watch(userProvider);
    final travelLogNotifier = ref.read(travelLogProvider.notifier);

    final user = allUsers.firstWhere(
      (u) => u.id == travelLog.userId,
      orElse: () => allUsers.first,
    );

    final isLiked =
        currentUser != null && travelLog.isLikedByUser(currentUser.id);

    return AspectRatio(
      aspectRatio: 182 / 262,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/log_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    image: DecorationImage(
                      image: AssetImage(
                        travelLog.isVideoType && travelLog.videoCoverUrl != null
                            ? travelLog.videoCoverUrl!
                            : travelLog.mediaUrl,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child:
                      travelLog.isVideoType
                          ? Icon(AliIcons.iconPlayFill)
                              .iconSize(22.sp)
                              .iconColor(Colors.white.withValues(alpha: 0.8))
                              .center()
                          : null,
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                alignment: Alignment.centerLeft,
                child: Text(
                  travelLog.content,
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.black87,
                    height: 1.2,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.start,
                ),
              ),
              Container(
                padding: EdgeInsets.all(8.w),
                child:
                    [
                      Container(
                        width: 28.w,
                        height: 28.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          image: DecorationImage(
                            image: AssetImage(user.avatar),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Expanded(
                        child: Text(
                          user.username,
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.black87,
                            fontWeight: FontWeight.w500,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      [
                        Text(
                          '${travelLog.likeCount}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: isLiked ? Colors.red : Colors.black,
                            fontWeight:
                                isLiked ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Icon(AliIcons.iconGood)
                            .iconSize(18.sp)
                            .iconColor(isLiked ? Colors.red : Colors.grey),
                      ].toRow().inkWell(
                        onTap: () async {
                          if (currentUser != null) {
                            await travelLogNotifier.toggleLike(
                              travelLog.logId,
                              currentUser.id,
                            );
                          }
                        },
                      ),
                    ].toRow(),
              ),
            ].toColumn(),
      ),
    ).inkWell(
      onTap: () {
        GoRouter.of(context).push('/journey-detail/${travelLog.logId}');
      },
    );
  }

  Widget _buildShareContent(UserDataEntity currentUser) {
    final travelLogs = ref.watch(travelLogProvider);
    final userLogs =
        travelLogs.where((log) => log.userId == currentUser.id).toList();

    if (userLogs.isEmpty) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child:
            Image.asset(
              'assets/resources/no.png',
              width: 176.w,
              height: 176.w,
            ).center(),
      );
    }

    final itemHeight = 262.h;
    final itemSpacing = 12.h;
    final columnCount = (userLogs.length / 2).ceil();
    final totalHeight = columnCount * (itemHeight + itemSpacing);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      height: totalHeight,
      child: [
        Expanded(
          child:
              [
                for (int i = 0; i < userLogs.length; i += 2)
                  if (i < userLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(userLogs[i]),
                    ),
              ].toColumn(),
        ),
        SizedBox(width: 12.w),
        Expanded(
          child:
              [
                for (int i = 1; i < userLogs.length; i += 2)
                  if (i < userLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(userLogs[i]),
                    ),
              ].toColumn(),
        ),
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }
}
